package com.cras.webcam.http.handler;

import android.util.Log;

import com.cras.webcam.http.ChannelHandler;

import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
 * 接收请求，建立连接的处理器
 * @author cras
 *
 */
public class AcceptHandler implements ChannelHandler {
	private static final String LOG_TAG = AcceptHandler.class.getName();

	@Override
	public void handle(SelectionKey key) {
		// 有客户端连接请求时
		if(key.isAcceptable()){
			// 返回创建此键的通道，接受客户端建立连接的请求，并返回 SocketChannel 对象
			ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
			try {
				SocketChannel sc = ssc.accept();
				if(null == sc) return;
				sc.configureBlocking(false);
				//连接建立起后，设置处理请求处理器
				RequestHandler rh = new RequestHandler(new HandlerContext(sc, false));
				// 注册到selector
				sc.register(key.selector(), SelectionKey.OP_READ, rh);
				Log.i(LOG_TAG,"accept....");
			} catch (Exception e) {
				Log.e(LOG_TAG,"accept request",e);
			}
		}
	}
	
}
